﻿using DataSyncCommon;
using Quartz;
using System;
using System.Threading.Tasks;
using System.Collections;
using System.Data;
using System.IO; 
using System.Xml;
using SupDataSync.Model;
using DataSyncCommon.Model;
using SqlSugar;
using DataSyncCom;
using System.Linq;
using System.Collections.Generic;

namespace ConsoleCore
{
    class OrderJob : IJob
    {
        public Task Execute(IJobExecutionContext context)
        {
            DoOrder();
            return Task.FromResult(true);
        }
        /// <summary>
        /// 1.循环所有供应商分别拉取 贵州和四川订单
        /// 1.拉取贵州 四川中烟订单
        /// 存储数据 供应商 客户 订单编号 和数据库对比是否已经拉取了
        /// </summary>
        private void DoOrder()
        {
            log($"执行拉取中烟订单{DateTime.Now}");
            var dt = DateTime.Now;
            var sdt = dt.AddDays(1 - dt.Day);
            var edt = sdt.AddMonths(1).AddDays(-1);
            using (var db = DbHelperMySql.GetSqlSugarDb())
            {
                try
                {
                    var ifs = db.Queryable<interfacedefine>().Where(x => x.METHODNAME == "getMatAccPurchaseInfoBill" && x.CUSTOMERCODE == "20510002").ToList();
                    var sups = db.Queryable<ba_supplier>().Where(x=>x.Customercode== "20510002").ToList();
                    var saleorders = db.Queryable<sale_order_main>().Where(x => x.CREATION_DATE >= sdt && x.CREATION_DATE <= edt && !string.IsNullOrEmpty(x.OUT_ORDER_NO)).ToList();
                    var lqbills = saleorders.Select(x => x.OUT_ORDER_NO).ToList();//已有的
                    var users = db.Queryable<t_pms_user>().Where(x => x.msgtype.Contains("order")).ToList();//有维护
                    var userm = db.Queryable<t_pms_user>().Where(x => x.F_USER_TYPE == 2).ToList();
                    var nomos = db.Queryable<sale_order_monitor>().Select(x => x.bill_no).ToList();//获取未发送的.Where(x => x.IS_CONFIRM == 0)
                    foreach (var ifmode in ifs)
                    {
                        foreach (var sup in sups)
                        {
                            var ds = GetOrderFromIface(DateTime.Now.AddMonths(-1).ToString("yyyyMM"), DateTime.Now.AddMonths(1).ToString("yyyyMM"), ifmode.CUSTOMERCODE, db, sup, ifmode);
                            log($"开始获取供应商【{sup.SYS_CD_NM}】客户为【{ifmode.CUSTOMERNAME}】");
                            if (ds != null && ds.Tables.Count > 2)
                            {
                                DataTable dtMain = ds.Tables["DATA"];
                                var bills = new Dictionary<string, string>();
                                foreach (DataRow dr in dtMain.Rows)
                                {
                                    var billno = dr["BILL_NO"].ToString();
                                    var month = dr["PLAN_MONTH"].ToString();
                                    if (!lqbills.Contains(billno))
                                    {
                                        bills.Add(billno, month);
                                    }
                                }
                                var phone = "";
                                if (users.Count != 0)
                                {
                                    phone = string.Join(',', users.Where(x=>x.TenantID==sup.TenantID).Select(x => x.F_CODE).ToArray());
                                }
                                else {
                                    phone = userm.Where(x=>x.TenantID==sup.TenantID).First().F_CODE;
                                }
                                log($"----------获取到供应商【{sup.SYS_CD_NM}】客户为【{ifmode.CUSTOMERNAME}】订单编号为【{string.Join(",", bills.Keys.ToArray())}】");
                                if (bills.Keys.Count == 0) { log("该供应商已经全部提取"); }
                                var mos = new List<sale_order_monitor>();
                                foreach (var bi in bills)
                                {
                                    if (!nomos.Contains(bi.Key)&& !lqbills.Contains(bi.Key))
                                    {
                                        var monitor = new sale_order_monitor
                                        {
                                            SALE_ORDER_M_ID = Guid.NewGuid().ToString("N"),
                                            bill_no = bi.Key,
                                            month=bi.Value,
                                            creattime = DateTime.Now,
                                            customercode = ifmode.CUSTOMERCODE,
                                            CUSTOMERNAME = ifmode.CUSTOMERNAME,
                                            suppliername = sup.SYS_CD_NM,
                                            phone = phone,
                                            teanaid=sup.TenantID
                                        };
                                        mos.Add(monitor);
                                    }
                                }
                                if (mos.Count != 0)
                                {
                                    log($"----------插入到供应商【{sup.SYS_CD_NM}】客户为【{ifmode.CUSTOMERNAME}】订单编号为【{string.Join(",", mos.Select(x=>x.bill_no).ToArray())}");
                                    var s = db.Insertable(mos).ExecuteCommand();
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    log(ex.Message);
                    throw;
                }
            }
        }
        private void log(string str)
        {
            Console.WriteLine(str);
            LogHelper.CreateLoger().Error(str);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="startMonth"></param>
        /// <param name="endMonth"></param>
        /// <param name="CustomerCode"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        public DataSet GetOrderFromIface(string startMonth, string endMonth, string CustomerCode, SqlSugarClient db,ba_supplier sup,interfacedefine ifmodel)
        {
            //todo ERP接口获取
            try
            {
                startMonth = startMonth.Replace("-", "");
                endMonth = endMonth.Replace("-", "");

                //请求xml
                string reqxml = @"<?xml version='1.0' encoding='gbk'?>
<DATASET>
  <HEAD>
    <MSG_ID>CYZY_ESB_SERVICES_{0}</MSG_ID>
    <STATE_CODE></STATE_CODE>
    <STATE_DESC></STATE_DESC>
    <WS_MARK>CYZY_ESB_SERVICES</WS_MARK>
    <WS_METHOD>getMatAccPurchaseInfoBill</WS_METHOD>
    <WS_PARAM>XML</WS_PARAM>
    <CURR_TIME>{1}</CURR_TIME>
    <CURR_USER>PBMS</CURR_USER>
  </HEAD>
  <DATALIST>
    <DATA>
      <SUPPLIER_CODE>{2}</SUPPLIER_CODE>
      <START_DATE>{3}</START_DATE>
      <END_DATE>{4}</END_DATE>
    </DATA>
  </DATALIST>
</DATASET>";
                string TempId = DateTime.Parse(DateTime.Now.ToCstTime().ToString("yyyy-MM-dd HH:mm:ss")).ToString("yyyyMMddHHmmss");               
                reqxml = string.Format(reqxml, TempId, DateTime.Parse(DateTime.Now.ToCstTime().ToString("yyyy-MM-dd HH:mm:ss")).ToString("yyyy-MM-dd HH:mm:ss"),
                    sup.SYS_USER_CD, startMonth, endMonth);
                Hashtable ht = new Hashtable();
                ht.Add(ifmodel.PARANAME, reqxml);//"strXml","reqXml","httpXml"
                XmlDocument xml = WebServesClient.QueryPostWebService(ifmodel.URL, ifmodel.METHODNAME, ht);
                DataSet ds = new DataSet();
                TextReader tr = new StringReader(xml.InnerXml);
                ds.ReadXml(tr);
                XmlNode CodeNode = xml.SelectSingleNode("/DATASET/HEAD/STATE_CODE");
                XmlNode DescNode = xml.SelectSingleNode("/DATASET/HEAD/STATE_DESC"); 
                var code= CodeNode == null ? "" : CodeNode.InnerText;
                var desc = DescNode == null ? "" : DescNode.InnerText; 
                log($"{sup.SYS_CD_NM}获取订单反馈代码{code}描述{desc}");
                return ds;
            }
            catch (Exception ex)
            {
                log(ex.Message);
                return null;
            }
        }

    }
}
